package com.ruoyi.config.jwt;

/**
 * @author: xiaYZ 2024/3/12
 * @version: 1.0
 */

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * description: 接口端的方法拦截器
 * version: 1.0
 * date: 2022/5/26 11:45
 * author: xiaYZ
 **/

public class ApiHandlerInterceptor implements HandlerInterceptor {

    private static final List<String> API_EXCLUDE_PATH = Arrays.asList("/testAction");

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        for (String path : API_EXCLUDE_PATH) {
            if (uri.contains(path)) {
                return true;
            }
        }
        String token = request.getHeader("token");
        HashMap<String, Object> map = new HashMap<>(8);
        try {
            if (token != null) {
                //token计算出用户名
                String userName = TokenUtil.getUserName(token);
                return true;
            } else {
                map.put("code", 500);
                map.put("msg", "请求头中没有token");
            }
        } catch (ExpiredJwtException e) {
            map.put("code", 500);
            map.put("msg", "token已过期");
        } catch (Exception e) {
            map.put("code", 500);
            map.put("msg", "token校验失败");
            e.printStackTrace();
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSONUtil.toJsonStr(map));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}